package com.zhiletu.collect.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.log4j.Logger;


/**
 *
 * @Title: shell 相关操作类
 * @Package com.zhiletu.collect.util
 * @Description: TODO
 * @author zhiletu.com
 * @date 2021年3月11日
 * @version V1.0
 */
public class Shell {
	private static final Logger log = Logger.getLogger(Shell.class);

//	public static void main(String args[]) throws Exception { 
//	} 

	/**
	 * 执行shell，返回执行成功结果 同时打印命令返回结果
	 * @param command
	 * @return
	 */
	public static boolean execShell(String command) {
		Process process = null;
		BufferedReader input = null;
		boolean flag = true;
		try {
			try {
				process = Runtime.getRuntime().exec(command);
				input = new BufferedReader(new InputStreamReader(process.getInputStream()));
				String line = "";
				while ((line = input.readLine()) != null) {
					log.info(line);
				}
			}
			catch (Throwable e) {
				flag = false;
				log.error(Shell.class, e);
			}
		}
		finally {
			try {
				input.close();
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}

		return flag;
	}

	/**
	 * 执行shell命令
	 * @param shellString
	 * @return true 执行成功 false 执行失败
	 */
	public static boolean callShell(String shellString) {
		boolean flag = true;
		Process process = null;
		try {
			process = Runtime.getRuntime().exec(shellString);

		}
		catch (Throwable e) {
			flag = false;
			log.error("call shell failed. " + e);
		}
		finally {
			int exitValue = 1;
			try {
				exitValue = process.waitFor();
			}
			catch (InterruptedException e) {
				log.error(e);
			}
			if (0 != exitValue) {
				flag = false;
				log.error("call shell failed. error code is :" + exitValue + " command: " + shellString);
			}
		}

		return flag;
	}

	/**
	 * 执行shell，返回执行成功结果 同时打印命令返回结果
	 * @param command
	 * @return
	 */
	public static String execCommand(String command) {
		Process process = null;
		BufferedReader input = null;
		StringBuilder sd = new StringBuilder();
		try {
			try {
				process = Runtime.getRuntime().exec(command);
				input = new BufferedReader(new InputStreamReader(process.getInputStream()));
				String line = "";
				while ((line = input.readLine()) != null) {
					sd.append(line);
				}
			}
			catch (Throwable e) {
				e.printStackTrace();
			}
		}
		finally {
			try {
				input.close();
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}

		return sd.toString();
	}
}